<!--
  * 对账司机
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.related_id" placeholder="司机" allow-clear @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="订单类型" class="smart-margin-bottom0">
            <a-select v-model:value="queryForm.order_type" :dropdownMatchSelectWidth="false" placeholder="账单类型" allow-clear>
              <a-select-option :value="1">销售</a-select-option>
              <a-select-option :value="2">退货</a-select-option>
              <a-select-option :value="3">换货</a-select-option>
              <a-select-option :value="4">订货</a-select-option>
              <a-select-option :value="5">订退</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="交账状态" class="smart-margin-bottom0">
            <a-select v-model:value="queryForm.is_account" :dropdownMatchSelectWidth="false" placeholder="交账状态" allow-clear>
              <a-select-option :value="1">未交账</a-select-option>
              <a-select-option :value="2">已交账</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->
  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper" style="margin-bottom: 10px">
    <a-row>
      <a-col :span="10">
        <a-row>
          <a-col :span="2"><h1>出库</h1> </a-col>
          <a-col :span="22">
            <a-descriptions title="" layout="vertical" :column="4">
              <a-descriptions-item label="商品总数">
                <text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="正库商品数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.main_order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="处理库商品数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.advent_order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="商品总货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="正库商品货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.main_order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="处理库商品货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.advent_order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="配送人(个)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ out_data?.order_driver_ids }}</text></a-descriptions-item
              >
            </a-descriptions>
          </a-col>
        </a-row>
      </a-col>
      <a-col :span="1">
        <div style="display: inline-block; width: 1px; height: 140px; background: rgba(0, 0, 0, 0.1)"></div>
      </a-col>
      <a-col :span="13">
        <a-row>
          <a-col :span="2"><h1>拒签/回库</h1> </a-col>
          <a-col :span="22">
            <a-descriptions title="" layout="vertical" :column="5">
              <a-descriptions-item label="商品总数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="正库商品数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.main_order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="处理库商品数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.advent_order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="过期库商品数"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.expired_order_goods_num }}</text></a-descriptions-item
              >
              <a-descriptions-item label="商品总货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="正库商品货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.main_order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="处理库商品货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.advent_order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="过期库商品货值(元)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.expired_order_goods_value }}</text></a-descriptions-item
              >
              <a-descriptions-item label="配送人(个)"
                ><text style="color: rgba(46, 87, 223, 0.863); font-weight: bold; font-size: 14px">{{ return_data?.order_driver_ids }}</text></a-descriptions-item
              >
            </a-descriptions>
          </a-col>
        </a-row>
      </a-col>
    </a-row>
  </a-card>

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="onSubmit" :disabled="selectedRowKeys.length === 0" type="primary" v-privilege="'reconciliation:driver:check'">
          <template #icon>
            <PlusOutlined />
          </template>
          交账
        </a-button> -->

        <a-button @click="onExport" type="primary" v-privilege="'reconciliation:driver:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{ fixed: true, hideSelectAll: true, selectedRowKeys: selectedRowKeys, onSelect: onSelectChange, getCheckboxProps: getCheckboxProps }" @expand="onExpand">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'name'">
            <template v-if="record.level === expandLevel.ORDER.value">
              <div class="order-name">
                <CopyText :text="text">
                  <a class="order-no" @click="detail(record)" :style="{ color: '#87d068' }" v-if="record.order_type === 1">{{ text }} <span>[销]</span> <span v-if="record.is_abnormal === 2" style="color: red">[异]</span> </a>
                  <a class="order-no" @click="detail(record)" :style="{ color: '#108ee9' }" v-if="record.order_type === 2">{{ text }} <span>[退]</span> <span v-if="record.is_abnormal === 2" style="color: red">[异]</span></a>
                  <a class="order-no" @click="detail(record)" :style="{ color: '#108ee9' }" v-if="record.order_type === 3">{{ text }} <span>[换]</span> <span v-if="record.is_abnormal === 2" style="color: red">[异]</span></a>
                  <a class="order-no" @click="detail(record)" :style="{ color: '#2db7f5' }" v-if="record.order_type === 4">{{ text }} <span>[订]</span> <span v-if="record.is_abnormal === 2" style="color: red">[异]</span></a>
                  <a class="order-no" @click="detail(record)" :style="{ color: '#1667f5' }" v-if="record.order_type === 5">{{ text }} <span>[订退]</span> <span v-if="record.is_abnormal === 2" style="color: red">[异]</span></a>
                </CopyText>
              </div>
              <div> {{ record.store_name }} </div>
            </template>
            <template v-if="record.level === expandLevel.DATE.value">
              <span>{{ text }}</span>
              <span v-if="queryForm.is_account == 2">
                已交账
                <span style="color: #f00; font-weight: bold">{{ _.filter(record.children, { is_account: 2 }).length }}</span>
              </span>
              <span v-else>
                未交
                <span style="color: #f00; font-weight: bold">{{ _.filter(record.children, { is_account: 1 }).length }}</span>
              </span>
            </template>
            <template v-if="record.level === expandLevel.PERSON.value">
              <span>{{ text }}</span
              ><span v-if="record.escort_driver_name">({{ record.escort_driver_name }})</span>
            </template>
          </template>
          <template v-if="column.dataIndex === 'is_account' && record.level === expandLevel.ORDER.value">
            <template v-if="record.is_sign == 1">
              <a-tag color="#87d068" v-if="record.is_account === 2">已交账</a-tag>
              <a-tag color="#f50" v-if="record.is_account === 1">未交账</a-tag>
            </template>
            <template v-else>
              <a-tag color="red" v-if="record.is_account === 1">待签收</a-tag>
            </template>
          </template>
          <template v-if="column.dataIndex === 'unpaid_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.unpaid_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.unpaid_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'sign_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.sign_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.sign_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'return_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.return_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.return_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'unpaid_advance_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.unpaid_advance_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.unpaid_advance_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'credit_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.credit_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.credit_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'unpaid_cash_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.unpaid_cash_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.unpaid_cash_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'unpaid_company_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.unpaid_company_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.unpaid_company_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'gift_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.gift_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.gift_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'cash_pledge_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.cash_pledge_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.cash_pledge_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <template v-if="column.dataIndex === 'abnormal_amount'">
            <div v-if="record.level !== expandLevel.ORDER.value">
              <span style="color: #52c41a">{{ record.abnormal_amount_pos }}</span
              >/
              <span style="color: #f5222d">{{ record.abnormal_amount_neg }}</span>
            </div>
            <div v-else>{{ text }}</div>
          </template>
          <!-- <template v-if="column.dataIndex === 'abnormal_amount'">
            <span style="color: #f00; font-weight: bold">{{ text }}</span>
          </template> -->
          <template v-if="column.dataIndex === 'abnormal_num'">
            <span style="color: #f00; font-weight: bold">{{ text }}</span>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>已选</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.unpaid_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.unpaid_amount_neg }}</span>
                </div>
              </a-table-summary-cell>
              <a-table-summary-cell>{{ totalSelectedRowData.orderGoodsNum }}</a-table-summary-cell>
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.sign_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.sign_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <!-- 订单商品数量 -->
              <a-table-summary-cell>{{ totalSelectedRowData.orderSignGoodsNum }}</a-table-summary-cell>
              <!-- 实际签收商品数量 -->
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.return_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.return_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell>{{ totalSelectedRowData.return_num }}</a-table-summary-cell>
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.unpaid_advance_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.unpaid_advance_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.credit_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.credit_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.unpaid_cash_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.unpaid_cash_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.unpaid_company_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.unpaid_company_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.gift_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.gift_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.cash_pledge_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.cash_pledge_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalSelectedRowData.abnormal_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalSelectedRowData.abnormal_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <!-- <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ totalSelectedRowData.abnormal_amount }}</span>
              </a-table-summary-cell> -->
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ totalSelectedRowData.abnormalNum }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
            <a-table-summary-row>
              <a-table-summary-cell>合计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <div>
                  <span style="color: #52c41a">{{ totalTableData.unpaid_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.unpaid_amount_neg }}</span>
                </div>
              </a-table-summary-cell>
              <a-table-summary-cell>{{ totalTableData.orderGoodsNum }}</a-table-summary-cell>
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.sign_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.sign_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <!-- 订单商品数量 -->
              <a-table-summary-cell>{{ totalTableData.orderSignGoodsNum }}</a-table-summary-cell>
              <!-- 实际签收商品数量 -->
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.return_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.return_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell>{{ totalTableData.return_num }}</a-table-summary-cell>
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.unpaid_advance_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.unpaid_advance_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.credit_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.credit_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.unpaid_cash_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.unpaid_cash_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.unpaid_company_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.unpaid_company_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.gift_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.gift_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.cash_pledge_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.cash_pledge_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <a-table-summary-cell
                ><div>
                  <span style="color: #52c41a">{{ totalTableData.abnormal_amount_pos }}</span
                  >/
                  <span style="color: #f5222d">{{ totalTableData.abnormal_amount_neg }}</span>
                </div></a-table-summary-cell
              >
              <!-- <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ totalTableData.abnormal_amount }}</span>
              </a-table-summary-cell> -->
              <a-table-summary-cell>
                <span style="color: #f00; font-weight: bold">{{ totalTableData.abnormalNum }}</span>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>

    <DriverDetailsModal ref="detailRef" />
  </a-card>
</template>
<script setup lang="ts">
import dayjs from 'dayjs'
import _ from 'lodash'
import BigNumber from 'bignumber.js'
import { Modal, message } from 'ant-design-vue'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import Select from '@/components/business/select/index.vue'
import DriverDetailsModal from './components/driver-details-modal.vue'
import { driverAccountApi } from '@/api/business/finance/reconciliation-api'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { TIME_RANGE_PRESETS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
import { treeToList, findPath, filter as treeFilter } from '@/utils/tree-util'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useLoadingStore } from '@/store/modules/loading-store'
import { errorSentry } from '@/lib/error-sentry'
const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()

// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize({ pagination: false })

// ---------------------------- 表格列 ----------------------------
const columns = ref([
  {
    title: '',
    dataIndex: 'expand',
    width: 30
  },
  {
    title: '司机(协送人)',
    dataIndex: 'name',
    width: 320
  },
  {
    title: '交账状态',
    dataIndex: 'is_account'
  },
  {
    title: '订单金额',
    dataIndex: 'unpaid_amount'
  },
  {
    title: '订单商品数量',
    dataIndex: 'orderGoodsNum',
    width: 150
  },
  {
    title: '实际签收金额',
    dataIndex: 'sign_amount',
    width: 150
  },

  {
    title: '实际签收商品数量',
    dataIndex: 'orderSignGoodsNum',
    width: 150
  },
  {
    title: '回库金额',
    dataIndex: 'return_amount'
  },
  {
    title: '回库数量',
    dataIndex: 'return_num'
  },

  {
    title: '预付款',
    dataIndex: 'unpaid_advance_amount'
  },
  {
    title: '欠款',
    dataIndex: 'credit_amount'
  },
  {
    title: '现金',
    dataIndex: 'unpaid_cash_amount'
  },
  {
    title: '对公',
    dataIndex: 'unpaid_company_amount'
  },
  {
    title: '0元赠',
    dataIndex: 'gift_amount'
  },
  {
    title: '押金',
    dataIndex: 'cash_pledge_amount'
  },
  {
    title: '异常金额',
    dataIndex: 'abnormal_amount'
  },
  {
    title: '异常数量',
    dataIndex: 'abnormal_num'
  },
  {
    title: '备注',
    dataIndex: 'remark'
  }
])
function getCheckboxProps(record) {
  return {
    disabled: record.is_account === 2
  }
}

// ---------------------------- 查询数据表单和方法 ----------------------------

// 定义折叠层级
const expandLevel = {
  PERSON: {
    value: 1,
    prefix: 'person_'
  },
  DATE: {
    value: 2,
    prefix: 'date_'
  },
  ORDER: {
    value: 3,
    prefix: 'order_'
  }
}

/* 把任意金额字段拆成正、负两份和 */
function posNegSum(list: any[], key: string) {
  return list.reduce(
    (acc, raw) => {
      const v = new BigNumber(raw[key] || 0)
      if (v.isPositive()) {
        acc.pos = acc.pos.plus(v)
      } else {
        acc.neg = acc.neg.plus(v)
      }
      return acc
    },
    { pos: new BigNumber(0), neg: new BigNumber(0) }
  )
}

/* 把一个「子数组」里所有需要拆的字段一次算完，返回 { xxx_pos, xxx_neg } */
function buildPosNegTotal(children: any[], keys: string[]) {
  return keys.reduce(
    (total, k) => {
      const { pos, neg } = posNegSum(children, k)
      total[`${k}_pos`] = pos.toString()
      total[`${k}_neg`] = neg.toString()
      return total
    },
    {} as Record<string, string>
  )
}
// 已选行
const totalSelectedRowData = computed(() => {
  const list = treeToList(tableData.value).filter((item) => selectedRowKeys.value.includes(item.key) && item.level === expandLevel.ORDER.value)
  const orderGoodsNum = {
    unit_type_1: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_num_unit_type_1 || 0))
    }, new BigNumber(0)),
    unit_type_2: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_num_unit_type_2 || 0))
    }, new BigNumber(0)),
    unit_type_3: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_num_unit_type_3 || 0))
    }, new BigNumber(0))
  }
  const orderSignGoodsNum = {
    unit_type_1: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_sign_num_unit_type_1 || 0))
    }, new BigNumber(0)),
    unit_type_2: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_sign_num_unit_type_2 || 0))
    }, new BigNumber(0)),
    unit_type_3: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item.order_sign_num_unit_type_3 || 0))
    }, new BigNumber(0))
  }
  const return_num_detail = {
    unit_type_1: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.return_num_detail?.unit_type_1 || 0))
    }, new BigNumber(0)),
    unit_type_2: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.return_num_detail?.unit_type_2 || 0))
    }, new BigNumber(0)),
    unit_type_3: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.return_num_detail?.unit_type_3 || 0))
    }, new BigNumber(0))
  }
  const abnormal_num_detail = {
    unit_type_1: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.abnormal_num_detail?.unit_type_1 || 0))
    }, new BigNumber(0)),
    unit_type_2: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.abnormal_num_detail?.unit_type_2 || 0))
    }, new BigNumber(0)),
    unit_type_3: list.reduce((sum, item) => {
      return sum.plus(new BigNumber(item?.abnormal_num_detail?.unit_type_3 || 0))
    }, new BigNumber(0))
  }

  /* 不再 reduce 原值，而是 reduce 分池字段 */
  const pos = list.reduce((sum, item) => sum.plus(item.unpaid_amount_pos || 0), new BigNumber(0))
  const neg = list.reduce((sum, item) => sum.plus(item.unpaid_amount_neg || 0), new BigNumber(0))

  const pos2 = list.reduce((sum, item) => sum.plus(item.sign_amount_pos || 0), new BigNumber(0))
  const neg2 = list.reduce((sum, item) => sum.plus(item.sign_amount_neg || 0), new BigNumber(0))

  const pos3 = list.reduce((sum, item) => sum.plus(item.return_amount_pos || 0), new BigNumber(0))
  const neg3 = list.reduce((sum, item) => sum.plus(item.return_amount_neg || 0), new BigNumber(0))

  const pos4 = list.reduce((sum, item) => sum.plus(item.unpaid_advance_amount_pos || 0), new BigNumber(0))
  const neg4 = list.reduce((sum, item) => sum.plus(item.unpaid_advance_amount_neg || 0), new BigNumber(0))

  const pos5 = list.reduce((sum, item) => sum.plus(item.credit_amount_pos || 0), new BigNumber(0))
  const neg5 = list.reduce((sum, item) => sum.plus(item.credit_amount_neg || 0), new BigNumber(0))

  const pos6 = list.reduce((sum, item) => sum.plus(item.unpaid_cash_amount_pos || 0), new BigNumber(0))
  const neg6 = list.reduce((sum, item) => sum.plus(item.unpaid_cash_amount_neg || 0), new BigNumber(0))

  const pos7 = list.reduce((sum, item) => sum.plus(item.unpaid_company_amount_pos || 0), new BigNumber(0))
  const neg7 = list.reduce((sum, item) => sum.plus(item.unpaid_company_amount_neg || 0), new BigNumber(0))

  const pos8 = list.reduce((sum, item) => sum.plus(item.gift_amount_pos || 0), new BigNumber(0))
  const neg8 = list.reduce((sum, item) => sum.plus(item.gift_amount_neg || 0), new BigNumber(0))

  const pos9 = list.reduce((sum, item) => sum.plus(item.cash_pledge_amount_pos || 0), new BigNumber(0))
  const neg9 = list.reduce((sum, item) => sum.plus(item.cash_pledge_amount_neg || 0), new BigNumber(0))

  const pos10 = list.reduce((sum, item) => sum.plus(item.abnormal_amount_pos || 0), new BigNumber(0))
  const neg10 = list.reduce((sum, item) => sum.plus(item.abnormal_amount_neg || 0), new BigNumber(0))

  return {
    unpaid_amount_pos: pos.toString(),
    unpaid_amount_neg: neg.toString(),
    sign_amount_pos: pos2.toString(),
    sign_amount_neg: neg2.toString(),
    return_amount_pos: pos3.toString(),
    return_amount_neg: neg3.toString(),
    unpaid_advance_amount_pos: pos4.toString(),
    unpaid_advance_amount_neg: neg4.toString(),
    credit_amount_pos: pos5.toString(),
    credit_amount_neg: neg5.toString(),
    unpaid_cash_amount_pos: pos6.toString(),
    unpaid_cash_amount_neg: neg6.toString(),
    unpaid_company_amount_pos: pos7.toString(),
    unpaid_company_amount_neg: neg7.toString(),
    gift_amount_pos: pos8.toString(),
    gift_amount_neg: neg8.toString(),
    cash_pledge_amount_pos: pos9.toString(),
    cash_pledge_amount_neg: neg9.toString(),
    abnormal_amount_pos: pos10.toString(),
    abnormal_amount_neg: neg10.toString(),
    orderGoodsNum: `${orderGoodsNum.unit_type_3}整 ${orderGoodsNum.unit_type_2}中 ${orderGoodsNum.unit_type_1}散`, // 订单商品数量
    orderSignGoodsNum: `${orderSignGoodsNum.unit_type_3}整 ${orderSignGoodsNum.unit_type_2}中 ${orderSignGoodsNum.unit_type_1}散`, // 实际签收商品数量
    return_num: `${return_num_detail.unit_type_3}整 ${return_num_detail.unit_type_2}中 ${return_num_detail.unit_type_1}散`, // 回库数量
    abnormalNum: `${abnormal_num_detail.unit_type_3}整 ${abnormal_num_detail.unit_type_2}中 ${abnormal_num_detail.unit_type_1}散` // 异常数量
  }
})

// 总计行
const totalTableData = computed(() => {
  // 提取所有订单商品数量和实际签收商品数量
  const orderGoodsNums = tableData.value.map((item) => item.orderGoodsNum)
  const orderSignGoodsNums = tableData.value.map((item) => item.orderSignGoodsNum)
  const return_num_details = tableData.value.map((item) => item.return_num)
  const abnormal_num_details = tableData.value.map((item) => item.abnormal_num)

  // 累加订单商品数量和实际签收商品数量
  const orderGoodsNum = {
    unit_type_1: orderGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('散')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_2: orderGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('整')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_3: orderGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('整')[0] || '0', 10) || 0), 0)
  }

  const orderSignGoodsNum = {
    unit_type_1: orderSignGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('散')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_2: orderSignGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('整')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_3: orderSignGoodsNums.reduce((sum, num) => sum + (parseInt(num.split('整')[0] || '0', 10) || 0), 0)
  }

  const return_num_detail = {
    unit_type_1: return_num_details.reduce((sum, num) => sum + (parseInt(num.split('散')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_2: return_num_details.reduce((sum, num) => sum + (parseInt(num.split('整')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_3: return_num_details.reduce((sum, num) => sum + (parseInt(num.split('整')[0] || '0', 10) || 0), 0)
  }

  const abnormal_num_detail = {
    unit_type_1: abnormal_num_details.reduce((sum, num) => sum + (parseInt(num.split('散')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_2: abnormal_num_details.reduce((sum, num) => sum + (parseInt(num.split('整')[0].split('中')[1] || '0', 10) || 0), 0),
    unit_type_3: abnormal_num_details.reduce((sum, num) => sum + (parseInt(num.split('整')[0] || '0', 10) || 0), 0)
  }

  const pos = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_amount_pos || 0), new BigNumber(0))
  const neg = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_amount_neg || 0), new BigNumber(0))

  const pos2 = tableData.value.reduce((sum, item) => sum.plus(item.sign_amount_pos || 0), new BigNumber(0))
  const neg2 = tableData.value.reduce((sum, item) => sum.plus(item.sign_amount_neg || 0), new BigNumber(0))

  const pos3 = tableData.value.reduce((sum, item) => sum.plus(item.return_amount_pos || 0), new BigNumber(0))
  const neg3 = tableData.value.reduce((sum, item) => sum.plus(item.return_amount_neg || 0), new BigNumber(0))

  const pos4 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_advance_amount_pos || 0), new BigNumber(0))
  const neg4 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_advance_amount_neg || 0), new BigNumber(0))

  const pos5 = tableData.value.reduce((sum, item) => sum.plus(item.credit_amount_pos || 0), new BigNumber(0))
  const neg5 = tableData.value.reduce((sum, item) => sum.plus(item.credit_amount_neg || 0), new BigNumber(0))

  const pos6 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_cash_amount_pos || 0), new BigNumber(0))
  const neg6 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_cash_amount_neg || 0), new BigNumber(0))

  const pos7 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_company_amount_pos || 0), new BigNumber(0))
  const neg7 = tableData.value.reduce((sum, item) => sum.plus(item.unpaid_company_amount_neg || 0), new BigNumber(0))

  const pos8 = tableData.value.reduce((sum, item) => sum.plus(item.gift_amount_pos || 0), new BigNumber(0))
  const neg8 = tableData.value.reduce((sum, item) => sum.plus(item.gift_amount_neg || 0), new BigNumber(0))

  const pos9 = tableData.value.reduce((sum, item) => sum.plus(item.cash_pledge_amount_pos || 0), new BigNumber(0))
  const neg9 = tableData.value.reduce((sum, item) => sum.plus(item.cash_pledge_amount_neg || 0), new BigNumber(0))

  const pos10 = tableData.value.reduce((sum, item) => sum.plus(item.abnormal_amount_pos || 0), new BigNumber(0))
  const neg10 = tableData.value.reduce((sum, item) => sum.plus(item.abnormal_amount_neg || 0), new BigNumber(0))

  return {
    unpaid_amount_pos: pos.toString(),
    unpaid_amount_neg: neg.toString(),
    sign_amount_pos: pos2.toString(),
    sign_amount_neg: neg2.toString(),
    return_amount_pos: pos3.toString(),
    return_amount_neg: neg3.toString(),
    unpaid_advance_amount_pos: pos4.toString(),
    unpaid_advance_amount_neg: neg4.toString(),
    credit_amount_pos: pos5.toString(),
    credit_amount_neg: neg5.toString(),
    unpaid_cash_amount_pos: pos6.toString(),
    unpaid_cash_amount_neg: neg6.toString(),
    unpaid_company_amount_pos: pos7.toString(),
    unpaid_company_amount_neg: neg7.toString(),
    gift_amount_pos: pos8.toString(),
    gift_amount_neg: neg8.toString(),
    cash_pledge_amount_pos: pos9.toString(),
    cash_pledge_amount_neg: neg9.toString(),
    abnormal_amount_pos: pos10.toString(),
    abnormal_amount_neg: neg10.toString(),
    orderGoodsNum: `${orderGoodsNum.unit_type_3}整 ${orderGoodsNum.unit_type_2}中 ${orderGoodsNum.unit_type_1}散`, // 订单商品数量
    orderSignGoodsNum: `${orderSignGoodsNum.unit_type_3}整 ${orderSignGoodsNum.unit_type_2}中 ${orderSignGoodsNum.unit_type_1}散`, // 实际签收商品数量
    return_num: `${return_num_detail.unit_type_3}整 ${return_num_detail.unit_type_2}中 ${return_num_detail.unit_type_1}散`, // 回库数量
    abnormalNum: `${abnormal_num_detail.unit_type_3}整 ${abnormal_num_detail.unit_type_2}中 ${abnormal_num_detail.unit_type_1}散` // 异常数量
  }
})

// 转换value
const toNumberKeys = [
  'unpaid_count', // 未交张数
  'unpaid_amount', // 未交金额
  'sign_amount', // 已交金额
  'unpaid_advance_amount', // 未交预付款金额
  'credit_amount', // 欠款金额
  'unpaid_cash_amount', // 未交现金金额
  'unpaid_company_amount', // 未交对公金额
  'abnormal_amount', // 未交异常金额
  'gift_amount', // 0元赠金额
  'cash_pledge_amount', // 押金金额
  'return_amount'
]
function transformValue(source: { [key: string]: any }, keys: string[] = toNumberKeys) {
  /* 1. 原逻辑保持不动 ---------------------------------------------------- */
  const result = keys.reduce((pre: any[], key: string) => {
    const value = Number(source[key])
    pre.push([key, isNaN(value) ? 0 : value])
    return pre
  }, [])

  const orderGoodsNum = `${source.order_num_unit_type_3}整 ${source.order_num_unit_type_2}中 ${source.order_num_unit_type_1}散`
  const orderSignGoodsNum = `${source.order_sign_num_unit_type_3}整 ${source.order_sign_num_unit_type_2}中 ${source.order_sign_num_unit_type_1}散`
  const return_num = `${source.return_num_detail?.unit_type_3}整 ${source.return_num_detail?.unit_type_2}中 ${source.return_num_detail?.unit_type_1}散`
  const abnormal_num = `${source.abnormal_num_detail?.unit_type_3}整 ${source.abnormal_num_detail?.unit_type_2}中 ${source.abnormal_num_detail?.unit_type_1}散`

  /* 2. 追加：订单层也拆正负 --------------------------------------------- */
  const posNegFields = keys.reduce(
    (acc, k) => {
      const v = new BigNumber(source[k] || 0)
      acc[`${k}_pos`] = v.isPositive() ? v.toString() : '0'
      acc[`${k}_neg`] = v.isNegative() ? v.toString() : '0'
      return acc
    },
    {} as Record<string, string>
  )

  /* 3. 返回：原字段 + 数量拼接字段 + 正负分池字段 ------------------------ */
  return Object.fromEntries([...result, ['orderGoodsNum', orderGoodsNum], ['orderSignGoodsNum', orderSignGoodsNum], ['return_num', return_num], ['abnormal_num', abnormal_num], ...Object.entries(posNegFields)])
}
// 聚合时间
function aggregateTime(list: any[]) {
  const list1 = _(list)
    .map((item) => {
      const transformedItem = transformValue(item)
      return {
        ...item,
        ...transformedItem,
        create_time_str: dayjs.unix(item.create_time).format('YYYY-MM-DD')
      }
    })
    .groupBy('create_time_str')
    .mapValues((item) => {
      /* 1. 金额字段拆正负 */
      const posNegTotal = buildPosNegTotal(item, toNumberKeys)

      // 累加订单商品数量和实际签收商品数量
      const orderGoodsNum = {
        unit_type_1: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_num_unit_type_1 || 0))
        }, new BigNumber(0)),
        unit_type_2: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_num_unit_type_2 || 0))
        }, new BigNumber(0)),
        unit_type_3: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_num_unit_type_3 || 0))
        }, new BigNumber(0))
      }
      const orderSignGoodsNum = {
        unit_type_1: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_sign_num_unit_type_1 || 0))
        }, new BigNumber(0)),
        unit_type_2: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_sign_num_unit_type_2 || 0))
        }, new BigNumber(0)),
        unit_type_3: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val.order_sign_num_unit_type_3 || 0))
        }, new BigNumber(0))
      }

      const return_num_detail = {
        unit_type_1: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_1 || 0))
        }, new BigNumber(0)),
        unit_type_2: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_2 || 0))
        }, new BigNumber(0)),
        unit_type_3: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_3 || 0))
        }, new BigNumber(0))
      }
      const abnormal_num_detail = {
        unit_type_1: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_1 || 0))
        }, new BigNumber(0)),
        unit_type_2: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_2 || 0))
        }, new BigNumber(0)),
        unit_type_3: item.reduce((sum, val) => {
          return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_3 || 0))
        }, new BigNumber(0))
      }

      const result = {
        name: item[0].create_time_str,
        key: `${expandLevel.DATE.prefix}${item[0].create_time}`,
        order_id: `${expandLevel.DATE.prefix}${item[0].create_time}`,
        p_key: `${expandLevel.PERSON.prefix}${item[0].related_id}`,
        level: expandLevel.DATE.value,
        create_time: item[0].create_time,
        children: _(item)
          .map((row) => Object.assign(row, { name: row.no, level: expandLevel.ORDER.value, order_id: `${expandLevel.ORDER.prefix}${row.order_id}`, key: `${expandLevel.ORDER.prefix}${row.id}`, p_key: `${expandLevel.DATE.prefix}${item[0].create_time}` }))
          .sortBy('is_account')
          .value()
      }
      return Object.assign(result, posNegTotal, {
        orderGoodsNum: `${orderGoodsNum.unit_type_3}整 ${orderGoodsNum.unit_type_2}中 ${orderGoodsNum.unit_type_1}散`,
        orderSignGoodsNum: `${orderSignGoodsNum.unit_type_3}整 ${orderSignGoodsNum.unit_type_2}中 ${orderSignGoodsNum.unit_type_1}散`,
        return_num: `${return_num_detail.unit_type_3}整 ${return_num_detail.unit_type_2}中 ${return_num_detail.unit_type_1}散`, // 回库数量
        abnormal_num: `${abnormal_num_detail.unit_type_3}整 ${abnormal_num_detail.unit_type_2}中 ${abnormal_num_detail.unit_type_1}散` // 异常数量
      })
    })
    .values()
    .sort((a, b) => b.create_time - a.create_time)
    .value()
  return list1
}
// 出库
const out_data = ref({
  order_goods_num: 0,
  main_order_goods_num: 0,
  advent_order_goods_num: 0,
  order_goods_value: 0,
  main_order_goods_value: 0,
  advent_order_goods_value: 0,
  order_driver_ids: 0
})
// 拒签/回库
const return_data = ref({
  order_goods_num: 0,
  main_order_goods_num: 0,
  advent_order_goods_num: 0,
  expired_order_goods_num: 0,
  order_goods_value: 0,
  main_order_goods_value: 0,
  advent_order_goods_value: 0,
  expired_order_goods_value: 0,
  order_driver_ids: 0
})
const rawList = ref<any[]>([])
const { queryForm, queryData, tableData, tableLoading, resetQuery, onSearch } = useQuery({
  fetchDataApi: async ({ filter }) => {
    const data = { ...filter }
    const res = await driverAccountApi.queryList({ ...data })
    rawList.value = res.data.list
    out_data.value = res.data.out_data
    return_data.value = res.data.return_data

    const list = _(res.data.list)
      .map((item) => {
        const transformedItem = transformValue(item)
        return {
          ...item,
          ...transformedItem
        }
      })
      .groupBy('related_id') // 司机分组
      .mapValues((item) => {
        //根据toNumberKeys构建一个对象，值为item中对应key的值
        const posNegTotal = buildPosNegTotal(item, toNumberKeys)

        // 累加订单商品数量和实际签收商品数量
        const orderGoodsNum = {
          unit_type_1: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_num_unit_type_1 || 0))
          }, new BigNumber(0)),
          unit_type_2: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_num_unit_type_2 || 0))
          }, new BigNumber(0)),
          unit_type_3: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_num_unit_type_3 || 0))
          }, new BigNumber(0))
        }
        const orderSignGoodsNum = {
          unit_type_1: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_sign_num_unit_type_1 || 0))
          }, new BigNumber(0)),
          unit_type_2: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_sign_num_unit_type_2 || 0))
          }, new BigNumber(0)),
          unit_type_3: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val.order_sign_num_unit_type_3 || 0))
          }, new BigNumber(0))
        }

        const return_num_detail = {
          unit_type_1: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_1 || 0))
          }, new BigNumber(0)),
          unit_type_2: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_2 || 0))
          }, new BigNumber(0)),
          unit_type_3: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.return_num_detail?.unit_type_3 || 0))
          }, new BigNumber(0))
        }
        const abnormal_num_detail = {
          unit_type_1: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_1 || 0))
          }, new BigNumber(0)),
          unit_type_2: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_2 || 0))
          }, new BigNumber(0)),
          unit_type_3: item.reduce((sum, val) => {
            return sum.plus(new BigNumber(val?.abnormal_num_detail?.unit_type_3 || 0))
          }, new BigNumber(0))
        }

        const result = {
          name: item[0].driver_name,
          key: `${expandLevel.PERSON.prefix}${item[0].related_id}`,
          order_id: `${expandLevel.PERSON.prefix}${item[0].related_id}`,
          level: expandLevel.PERSON.value,
          children: aggregateTime(item)
        }
        return Object.assign(result, posNegTotal, {
          orderGoodsNum: `${orderGoodsNum.unit_type_3}整 ${orderGoodsNum.unit_type_2}中 ${orderGoodsNum.unit_type_1}散`,
          orderSignGoodsNum: `${orderSignGoodsNum.unit_type_3}整 ${orderSignGoodsNum.unit_type_2}中 ${orderSignGoodsNum.unit_type_1}散`,
          return_num: `${return_num_detail.unit_type_3}整 ${return_num_detail.unit_type_2}中 ${return_num_detail.unit_type_1}散`, // 回库数量
          abnormal_num: `${abnormal_num_detail.unit_type_3}整 ${abnormal_num_detail.unit_type_2}中 ${abnormal_num_detail.unit_type_1}散` // 异常数量
        })
      })
      .values()
      .value()

    return {
      list,
      total: 0
    }
  },
  queryFormFilter: {
    related_id: null,
    create_time: TIME_RANGE_PRESETS.find((item) => item.key === 'today')?.value,
    order_type: null,
    is_account: null
  },
  queryFormOp: {}
})

// 展开行
function onExpand(expanded: boolean, record: any) {
  // 如果是折叠
  if (!expanded) return
  // 如果是展开
  if (record.children?.length > 0 || record.level === expandLevel.ORDER.value) return
}

onMounted(queryData)

// 驳回
function returnCancel(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要驳回【' + rowData.name + '】吗?',
    okText: '确定',
    okType: 'danger',
    onOk() {
      singleCancel(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleCancel(rowData) {
  try {
    loadingStore.show()
    const res = await driverAccountApi.driverCancelCheck({ id: rowData.id })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}

// ---------------------------- 交账 ----------------------------
const selectedRowKeys = ref<string[]>([])

function onSelectChange(record: any, selected: boolean) {
  updateSelectedOrderIds(record, selected)
  const treeFnConfig = { id: 'key', pid: 'p_key' }

  if (record.level === expandLevel.PERSON.value) {
    const allChildren = treeToList([record], treeFnConfig)
    const orderKeys = allChildren.filter((item) => item.level === expandLevel.ORDER.value && item.is_account !== 2).map((item) => item.key)
    const parentKeys = allChildren.filter((item) => item.level === expandLevel.PERSON.value || item.level === expandLevel.DATE.value).map((item) => item.key)

    if (selected) {
      selectedRowKeys.value = [...selectedRowKeys.value, ...orderKeys, ...parentKeys]
    } else {
      selectedRowKeys.value = selectedRowKeys.value.filter((key) => !orderKeys.includes(key) && !parentKeys.includes(key))
    }
    return
  }

  function searchPersonKey() {
    return findPath(tableData.value, ({ key }) => key === record.p_key, treeFnConfig).find(({ level }) => level === expandLevel.PERSON.value)?.key
  }

  function hasPersonKey() {
    const person_key = searchPersonKey()
    return selectedRowKeys.value.includes(person_key)
  }

  function getTreePathKeys() {
    const treePathKeys = findPath(tableData.value, (item) => item.key === record.key, treeFnConfig).map((item) => item.key)
    if (record.level === expandLevel.DATE.value) {
      const allChildren = treeToList([record], treeFnConfig)
      const orderKeys = allChildren.filter((item) => item.level === expandLevel.ORDER.value && item.is_account !== 2).map((item) => item.key)
      return [...treePathKeys, ...orderKeys]
    }
    return treePathKeys
  }

  function addKeys() {
    if (hasPersonKey()) {
      const recordKeys = getTreePathKeys()
      const keys = [...selectedRowKeys.value, ...recordKeys]
      selectedRowKeys.value = [...new Set(keys)]
    } else {
      selectedRowKeys.value = getTreePathKeys()
    }
  }

  function removeKeys() {
    const person_key = searchPersonKey()
    const sourceList = tableData.value.filter((item) => item.key === person_key)
    const list = treeFilter(
      sourceList,
      (item) => {
        return item.key !== record.key && selectedRowKeys.value.includes(item.key)
      },
      treeFnConfig
    )
    selectedRowKeys.value = treeToList(
      treeFilter(list, (item) => item.children?.length !== 0, treeFnConfig),
      treeFnConfig
    ).map((item) => item.key)
  }

  if (selected) {
    addKeys()
  } else {
    removeKeys()
  }
}
// ----
const selectedOrderIds = ref<string[]>([])
function updateSelectedOrderIds(record: any, selected: boolean) {
  const treeFnConfig = { id: 'order_id', pid: 'p_key' } // 修改 id 为 order_id
  const debouncedOnStatistics = _.debounce(onStatistics, 500)
  if (record.level === expandLevel.PERSON.value) {
    const allChildren = treeToList([record], treeFnConfig)
    const orderKeys = allChildren.filter((item) => item.level === expandLevel.ORDER.value && item.is_account !== 2).map((item) => item.order_id) // 修改为 order_id
    const parentKeys = allChildren.filter((item) => item.level === expandLevel.PERSON.value || item.level === expandLevel.DATE.value).map((item) => item.order_id) // 修改为 order_id

    if (selected) {
      selectedOrderIds.value = [...selectedOrderIds.value, ...orderKeys, ...parentKeys]
    } else {
      selectedOrderIds.value = selectedOrderIds.value.filter((key) => !orderKeys.includes(key) && !parentKeys.includes(key))
    }
    debouncedOnStatistics()
    return
  }

  function searchPersonKey() {
    return findPath(tableData.value, ({ order_id }) => order_id === record.p_key, treeFnConfig).find(({ level }) => level === expandLevel.PERSON.value)?.order_id // 修改为 order_id
  }

  function hasPersonKey() {
    const person_key = searchPersonKey()
    return selectedOrderIds.value.includes(person_key)
  }

  function getTreePathKeys() {
    const treePathKeys = findPath(tableData.value, (item) => item.order_id === record.order_id, treeFnConfig).map((item) => item.order_id) // 修改为 order_id
    if (record.level === expandLevel.DATE.value) {
      const allChildren = treeToList([record], treeFnConfig)
      const orderKeys = allChildren.filter((item) => item.level === expandLevel.ORDER.value && item.is_account !== 2).map((item) => item.order_id) // 修改为 order_id
      return [...treePathKeys, ...orderKeys]
    }
    return treePathKeys
  }

  function addKeys() {
    if (hasPersonKey()) {
      const recordKeys = getTreePathKeys()
      const keys = [...selectedOrderIds.value, ...recordKeys]
      selectedOrderIds.value = [...new Set(keys)]
    } else {
      selectedOrderIds.value = getTreePathKeys()
    }
  }

  function removeKeys() {
    const person_key = searchPersonKey()
    const sourceList = tableData.value.filter((item) => item.order_id === person_key) // 修改为 order_id
    const list = treeFilter(
      sourceList,
      (item) => {
        return item.order_id !== record.order_id && selectedOrderIds.value.includes(item.order_id) // 修改为 order_id
      },
      treeFnConfig
    )
    selectedOrderIds.value = treeToList(
      treeFilter(list, (item) => item.children?.length !== 0, treeFnConfig),
      treeFnConfig
    ).map((item) => item.order_id) // 修改为 order_id
  }

  if (selected) {
    addKeys()
    debouncedOnStatistics()
  } else {
    removeKeys()
    debouncedOnStatistics()
  }
}

async function onStatistics() {
  const keysId = selectedOrderIds.value
    .filter((item) => item.includes(expandLevel.ORDER.prefix))
    .map((item) => item.replace(expandLevel.ORDER.prefix, ''))
    .join(',')
  if (keysId) {
    try {
      const res = await driverAccountApi.accountStatistics({ order_ids: keysId })
      out_data.value = res.data.out_data
      return_data.value = res.data.return_data
    } catch (error) {
      console.error('接口调用失败:', error)
    }
  } else {
    queryData()
    console.log('没有有效的订单 ID，不调用接口')
  }
}

// -----

async function onSubmit() {
  const keysId = selectedRowKeys.value
    .filter((item) => item.includes(expandLevel.ORDER.prefix))
    .map((item) => item.replace(expandLevel.ORDER.prefix, ''))
    .join(',')
  if (!keysId) {
    message.error('无需要交账数据！')
    return
  }
  Modal.confirm({
    title: '交账',
    content: '点击确定即可提交',
    onOk: async () => {
      const params = {
        id: keysId
      }
      try {
        const res = await driverAccountApi.driverAccount(params)
        selectedRowKeys.value = []
        message.success(res.msg)
        onSearch()
      } catch (error) {
        if (error.data.length > 0) {
          Modal.error({
            title: '提示',
            content: '订单异常尚未审核。请先审核异常订单，再提交交账'
          })
        } else {
          message.error(error.msg)
        }
      } finally {
        return Promise.resolve()
      }
    }
  })
}

const detailRef = ref()
function detail(record) {
  detailRef.value.showDrawer(record)
}
const signRef = ref()
function signEdit(record) {
  signRef.value.showDrawer(record)
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const data = {
    related_id: queryForm.value.related_id,
    create_time: queryForm.value.create_time,
    order_type: queryForm.value.order_type,
    is_account: queryForm.value.is_account
  }
  driverAccountApi.exportXlsx(data)
}
</script>
<style lang="less" scoped>
.order-name {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-no {
  width: 245px;
}
.order-tag {
  flex: auto;
  display: flex;
  justify-content: start;
  align-items: center;
  gap: 4px;
}
</style>
